package cn.skyquant.quant4j.api.service;

import cn.skyquant.quant4j.api.dto.ResultDTO;
import cn.skyquant.quant4j.api.enums.ApiAccessType;
import cn.skyquant.quant4j.api.enums.BorkerType;
import cn.skyquant.quant4j.sdk.util.digest.AES;
import cn.skyquant.quant4j.sdk.util.http.HttpUtils;
import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public abstract class BaseServiceProxy {

    protected static final String default_urlfix = "https://service.skyquant.cn/quant4j-service";
    public static final String REFERER = "service.skyquant.cn";
    private final Map<String, String> headerMap = new ConcurrentHashMap<>();
    public static final String REFERER_key = "Referer";
    public static final String TOKEN_KEY = "token";
    public static final String CODE_KEY = "accountCode";
    public static final String BORKER_KEY = "borkerType";

    protected static final ResultDTO error = ResultDTO.error("网络异常");

    public BaseServiceProxy(String accountCode, BorkerType borkerType) {
        headerMap.put(ApiAccessType.class.getSimpleName(), ApiAccessType.APP.name());
        headerMap.put(REFERER_key, REFERER);
        headerMap.put(CODE_KEY,accountCode);
        headerMap.put(BORKER_KEY,borkerType.name());
    }

    protected final JSONObject post(String uri, Map<String, String> paramMap) {
        addToken();
        return HttpUtils.post(default_urlfix + uri, paramMap,null,headerMap);
    }

    protected final JSONObject get(String uri, Map<String, String> paramMap) {
        addToken();
        return HttpUtils.get(default_urlfix + uri, paramMap,null,headerMap);
    }

    protected final JSONObject put(String uri, Map<String, String> paramMap) {
        addToken();
        return HttpUtils.put(default_urlfix + uri, paramMap,null,headerMap);
    }

    protected final JSONObject delete(String uri) {
        addToken();
        return HttpUtils.delete(default_urlfix + uri,null,headerMap);
    }

    private void addToken(){
        try {
            headerMap.put(TOKEN_KEY,AES.encrypt(String.valueOf(System.currentTimeMillis())));
        } catch (Exception e) {

        }
    }

}
